using MultiAgentsClient.ChatDataStructures;
using MultiAgentsClient.Manager.DataModel;
using MultiAgentsClient.Service.WorkflowEngine;
using MultiAgentsShared;
using Newtonsoft.Json.Linq;

using static MultiAgentsClient.Manager.WorkflowManager;

namespace MultiAgentsClient.Manager;

public class WorkflowWebviewOperator : ManagerBase
{
    private readonly UserDataModel userDataModel;
    private readonly WorkflowDataModel workflowDataModel;

    #region events
    // recieve command from UI
    public record LoadWorkflowCommand(int WorkflowId);
    public record WorkflowReceiveMessageCommand(object Sender, string WorkflowJson);

    // send command to UI
    public record LoadWorkflowCompleteCommand(string JSCode);
    #endregion

    public WorkflowWebviewOperator(UserDataModel userDataModel, WorkflowDataModel workflowDataModel)
    {
        this.userDataModel = userDataModel;
        this.workflowDataModel = workflowDataModel;

        eventBus.Subscribe<LoadWorkflowCommand>(LoadWorkflow);
        eventBus.Subscribe<WorkflowReceiveMessageCommand>(WorkFlowWebMessageReceived);
    }

    public void LoadWorkflow(LoadWorkflowCommand cmd)
    {
        if (cmd.WorkflowId == 0)
        {
            return;
        }

        workflowDataModel.selectWorkflow = cmd.WorkflowId;
        string? workflowJson = workflowDataModel[cmd.WorkflowId]?.configJson;
        if (workflowJson == null)
        {
            return;
        }

        string jsCode = $"window.updateFlowFromJSON ({workflowJson});";
        eventBus.Publish(new LoadWorkflowCompleteCommand(jsCode));
    }

    public void WorkFlowWebMessageReceived(WorkflowReceiveMessageCommand cmd)
    {
        string workflowJson = cmd.WorkflowJson;
        try
        {
            BehaviorTreeConfig? workflowConfigDict = new(0, 0, "name", workflowJson);
            if (workflowConfigDict == null)
            {
                return;
            }

            eventBus.Publish(new UpdateWorkflowSubscriptionCommand(workflowConfigDict, userDataModel.Id));

            JObject jsonObj = JObject.Parse(workflowJson);
            string workflowName = jsonObj["WorkflowName"]?.ToString() ?? throw Debug.ShouldNotHappen();
            
            eventBus.Publish(new UpdateWorkflowCommand(workflowDataModel.selectWorkflow, workflowName, workflowJson));
        }
        catch (Exception ex)
        {
            Debug.LogLine($"Save workflow faild: {ex.Message}");
        }
    }
}
